import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/Layout.vue'
import Login from '@/views/login/index.vue'
import Home from '@/views/home/index.vue'
import Question from '@/views/question/index.vue'
import Video from '@/views/video/index.vue'
import User from '@/views/user/index.vue'
import store from '@/store/index.js'
import Search from '@/views/search/index.vue'
import Result from '@/views/search/Result.vue'
import Detail from '@/views/article/index.vue'
import Profile from '@/views/user/Profile.vue'
import Chat from '@/views/user/Chat.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/home',
    children: [
      { path: 'home', component: Home },
      { path: 'question', component: Question },
      { path: 'video', component: Video },
      { path: 'user', component: User }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/result/:kw',
    component: Result,
    props: true
  },
  {
    path: '/detail/:id',
    component: Detail,
    props: true
  },
  {
    path: '/profile',
    component: Profile
  },
  {
    path: '/chat',
    component: Chat
  }
]

const router = new VueRouter({
  routes
})

// 白名单列表（没有登录也可以访问）
const whiteList = ['/home', '/video']
router.beforeEach((to, from, next) => {
  const userInfo = store.state.login.userInfo
  if (to.path === '/login') {
    // 访问登录页面
    next()
  } else if (userInfo && userInfo.token && userInfo.refresh_token) {
    // 访问非登录页面，并且有token
    next()
  } else if (whiteList.includes(to.path)) {
    // 访问非登录页面，但是没有token，并且
    // 判断访问的路由路径是否在白名单里面
    next()
  } else {
    // 访问非登录页面，但是没有token，也不在白名单里面
    next('/login')
  }
})

export default router
